package com.hunantv.mglive.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.ShareConfigData;
import com.hunantv.mglive.ui.handle.TencentHandle;
import com.hunantv.mglive.ui.handle.WBHandle;
import com.hunantv.mglive.ui.handle.WXHandle;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.hunantv.mglive.utils.DownloadImage.IDownloadCallBack;

import org.json.JSONException;

/**
 * Created by QiuDa on 15/12/20.
 */
public class ShareUtil implements View.OnClickListener, IDownloadCallBack,HttpUtils.callBack {

    public static final int PLATFORM_QQ = 0;
    public static final int PLATFORM_QQ_ZONE = 1;
    public static final int PLATFORM_WECHAT = 2;
    public static final int PLATFORM_WECHAT_FRIEND = 3;
    public static final int PLATFORM_SINA = 4;
    public static final int PLATFORM_COPY = 5;

    public static final int TYPE_ACTOR = 0;//艺人空间
    public static final int TYPE_LIVE_PHONE = 1;//手机直播
    public static final int TYPE_LOOK = 2;//看妹子
    public static final int TYPE_LIVE_ROOM = 3;//空间直播
    public static final int TYPE_DYNAMIC = 4;//动态

    private HttpUtils mHttp;
    private int mShareType;
    private int mSharePLatForm;
    private String uId;
    private String token;
    private String bId;
    private String cId;
    private String aId;
    private String btype;

    private String mTitle;
    private String mDes;
    private String mImageUrl;
    private String mLinkUrl;

    //是否需要请求配置
    private boolean isNeedRequestConfig;

    private Context mContext;
    private Dialog mDialog;
    private Dialog mDialogFull;
    private TencentHandle mTencentHandle;

    public ShareUtil(Context mContext) {
        this.mContext = mContext;
        creatDialog(mContext);
        mTencentHandle = new TencentHandle(mContext);
    }

    private Dialog creatDialog(Context mContext) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_view_layout, null);
        List<ShareItemDeta> itemList = new ArrayList<>();
        itemList.add(new ShareItemDeta(R.drawable.share_qq, R.string.share_text_qq));
        itemList.add(new ShareItemDeta(R.drawable.share_qzone, R.string.share_text_qzone));
        itemList.add(new ShareItemDeta(R.drawable.share_wx, R.string.share_text_wx));
        itemList.add(new ShareItemDeta(R.drawable.share_moments, R.string.share_text_moments));
        itemList.add(new ShareItemDeta(R.drawable.share_sina, R.string.share_text_sina));
        itemList.add(new ShareItemDeta(R.drawable.share_link, R.string.share_text_link));
        setItemView(itemList, view, R.color.share_text_color);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        Dialog dialog = new Dialog(mContext, R.style.custom_dialog);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
        lp.x = 0;
        lp.y = 0;
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;

        view.setMinimumWidth(dm.widthPixels);
        window.setAttributes(lp);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        return dialog;
    }

    private Dialog creatFullDialog(Context mContext) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_full_view_layout, null);
        List<ShareItemDeta> itemList = new ArrayList<>();
        itemList.add(new ShareItemDeta(R.drawable.share_qq_full, R.string.share_text_qq));
        itemList.add(new ShareItemDeta(R.drawable.share_qzone_full, R.string.share_text_qzone));
        itemList.add(new ShareItemDeta(R.drawable.share_wx_full, R.string.share_text_wx));
        itemList.add(new ShareItemDeta(R.drawable.share_moments_full, R.string.share_text_moments));
        itemList.add(new ShareItemDeta(R.drawable.share_sina_full, R.string.share_text_sina));
        itemList.add(new ShareItemDeta(R.drawable.share_link_full, R.string.share_text_link));
        setItemView(itemList, view, R.color.white);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        Dialog dialog = new Dialog(mContext, R.style.custom_dialog_full);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.x = 0;
        lp.y = 0;
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        view.setMinimumWidth(dm.widthPixels);
        window.setAttributes(lp);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        return dialog;
    }

    private void setItemView(List<ShareItemDeta> itemList, View view, int textColor) {
        List<Integer> itemViews = new ArrayList<>();
        itemViews.add(R.id.v_share_item_qq);
        itemViews.add(R.id.v_share_item_qzone);
        itemViews.add(R.id.v_share_item_wx);
        itemViews.add(R.id.v_share_item_moments);
        itemViews.add(R.id.v_share_item_sina);
        itemViews.add(R.id.v_share_item_link);
        for (int i = 0; i < itemViews.size(); i++) {
            View groupV = view.findViewById(itemViews.get(i));
            ImageView ivIcon = (ImageView) groupV.findViewById(R.id.iv_share_item_icon);
            TextView tvText = (TextView) groupV.findViewById(R.id.tv_share_item_text);
            tvText.setTextColor(mContext.getResources().getColor(textColor));
            ShareItemDeta data = itemList.get(i);
            Glide.with(mContext).load(data.iconRes).fitCenter().into(ivIcon);
            tvText.setText(data.text);
            groupV.setOnClickListener(this);
        }

    }

    public void share(String uId,String token,int type,String bId,String aId,String cId,String btype) {
        if (mDialog != null) {
            if (mDialog.isShowing()) {
                return;
            }
        } else {
            mDialog = creatDialog(mContext);
        }
        mDialog.show();

        this.uId  = uId;
        this.token  = token;
        this.mShareType  = type;
        this.bId  = bId;
        this.aId  = aId;
        this.cId  = cId;
        this.btype  = btype;
        this.isNeedRequestConfig = true;
    }

    public void share(String title, String des, String image, String url) {
        if (mDialog != null) {
            if (mDialog.isShowing()) {
                return;
            }
        } else {
            mDialog = creatDialog(mContext);
        }
        mTitle = title;
        mDes = des;
        mImageUrl = image;
        mLinkUrl = url;
        this.isNeedRequestConfig = false;
        mDialog.show();

    }

    public void shareAsFull(String uId,String token,int type,String bId,String aId,String cId,String btype) {
        if (mDialogFull != null) {
            if (mDialogFull.isShowing()) {
                return;
            }
        } else {
            mDialogFull = creatFullDialog(mContext);
        }
        mDialogFull.show();

        this.uId  = uId;
        this.token  = token;
        this.mShareType  = type;
        this.bId  = bId;
        this.aId  = aId;
        this.cId  = cId;
        this.btype  = btype;
        this.isNeedRequestConfig = true;
    }


    @Override
    public void onClick(View v) {
            if(v.getId() == R.id.v_share_item_qq){
                if(isNeedRequestConfig){
                    this.mSharePLatForm = PLATFORM_QQ;
                    getShareConfig(this.uId, this.token, this.mShareType, this.mSharePLatForm, this.bId, this.cId, this.aId,this.btype);
                }else{
                    shareToQQ(mTitle, mDes,mLinkUrl ,mImageUrl);
                }
            }else if(v.getId() == R.id.v_share_item_qzone){
                if(isNeedRequestConfig){
                    this.mSharePLatForm = PLATFORM_QQ_ZONE;
                    getShareConfig(this.uId, this.token, this.mShareType, this.mSharePLatForm, this.bId, this.cId, this.aId,this.btype);
                }else{
                    shareToQzone(mTitle, mDes, mLinkUrl, mImageUrl);

                }
            }else if(v.getId() == R.id.v_share_item_wx){
                if(isNeedRequestConfig){
                    this.mSharePLatForm = PLATFORM_WECHAT;
                    getShareConfig(this.uId, this.token, this.mShareType, this.mSharePLatForm, this.bId, this.cId, this.aId,this.btype);
                }else{
                    shareToWX(mTitle, mDes, mLinkUrl, mImageUrl);

                }
            }else if(v.getId() == R.id.v_share_item_moments){
                if(isNeedRequestConfig){
                    this.mSharePLatForm = PLATFORM_WECHAT_FRIEND;
                    getShareConfig(this.uId, this.token, this.mShareType, this.mSharePLatForm, this.bId, this.cId, this.aId,this.btype);
                }else{
                    shareToMoments(mTitle, mDes, mLinkUrl, mImageUrl);
                }
            }else if(v.getId() == R.id.v_share_item_sina){
                if(isNeedRequestConfig){
                    this.mSharePLatForm = PLATFORM_SINA;
                    getShareConfig(this.uId, this.token, this.mShareType, this.mSharePLatForm, this.bId, this.cId, this.aId,this.btype);
                }else{
                    shareToSina(mTitle, mDes, mLinkUrl, mImageUrl);
                }
            }else if(v.getId() == R.id.v_share_item_link){
                if(isNeedRequestConfig){
                    this.mSharePLatForm = PLATFORM_COPY;
                    getShareConfig(this.uId,this.token,this.mShareType,this.mSharePLatForm,this.bId,this.cId,this.aId,this.btype);
                }else{
                    StringUtil.copy(mContext, mTitle + "  " + mLinkUrl);
                    Toast.makeText(mContext, "复制成功", Toast.LENGTH_SHORT).show();
                }
            }

        if(!isNeedRequestConfig){
            if (mDialog != null) {
                mDialog.dismiss();
            }
            if (mDialogFull != null) {
                mDialogFull.dismiss();
            }
        }


    }

    public void shareToSina(String title, String des, String linkUrl, String imageUrl) {
        Toast.makeText(mContext, "正在压缩图片...", Toast.LENGTH_SHORT).show();
        ShareData shareData = new ShareData();
        shareData.title = title;
        shareData.des = des;
        shareData.linkurl = linkUrl;
        shareData.imageurl = imageUrl;
        shareData.callBack = this;
        shareData.type = R.id.v_share_item_sina;
        DownloadImage downloadImage = new DownloadImage();
        LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<Runnable>();
        ExecutorService exec = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, blockingQueue);
        downloadImage.executeOnExecutor(exec,shareData);
//        downloadImage.execute(shareData);
    }

    public void shareToMoments(String title, String des, String linkUrl, String imageUrl) {
        Toast.makeText(mContext, "正在压缩图片...", Toast.LENGTH_SHORT).show();
        ShareData shareData = new ShareData();
        shareData.title = title;
        shareData.des = des;
        shareData.linkurl = linkUrl;
        shareData.imageurl = imageUrl;
        shareData.callBack = this;
        shareData.type = R.id.v_share_item_moments;
        DownloadImage downloadImage = new DownloadImage();
        LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<Runnable>();
        ExecutorService exec = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, blockingQueue);
        downloadImage.executeOnExecutor(exec,shareData);
//        downloadImage.execute(shareData);
    }

    public void shareToWX(String title, String des, String linkUrl, String imageUrl) {
        Toast.makeText(mContext, "正在压缩图片...", Toast.LENGTH_SHORT).show();
        ShareData shareData = new ShareData();
        shareData.title = title;
        shareData.des = des;
        shareData.linkurl = linkUrl;
        shareData.imageurl = imageUrl;
        shareData.callBack = this;
        shareData.type = R.id.v_share_item_wx;
        DownloadImage downloadImage = new DownloadImage();
        LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<Runnable>();
        ExecutorService exec = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, blockingQueue);
        downloadImage.executeOnExecutor(exec, shareData);
//        downloadImage.execute(shareData);
    }

    public void shareToQzone(String title, String des, String linkUrl, String imageUrl) {
        mTencentHandle.shareToQzone(title, des, linkUrl, imageUrl);
    }

    public void shareToQQ(String title, String des, String linkUrl, String imageUrl) {
        mTencentHandle.shareToQQ(title, des, linkUrl, imageUrl);
    }

    @Override
    public void callBack(ShareData shareData) {
        if (shareData != null) {
            if (shareData.type == R.id.v_share_item_wx) {
                WXHandle.getInstance(mContext).shareToWX(shareData.title, shareData.des, shareData.linkurl, shareData.bitmap);
            } else if (shareData.type == R.id.v_share_item_moments) {
                WXHandle.getInstance(mContext).shareToMoments(shareData.title, shareData.des, shareData.linkurl, shareData.bitmap);
            } else if (shareData.type == R.id.v_share_item_sina) {
                WBHandle.getWBHandle(mContext).shareToSinaWB(shareData.title, shareData.des, shareData.linkurl, shareData.bitmap);
            }
        }
    }


    public void dismiss() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        if (mDialogFull != null && mDialogFull.isShowing()) {
            mDialogFull.dismiss();
        }
    }


    /**
     * 获取分享配置信息
     */
    public void getShareConfig(String uId,String token,int type,int platForm,String bId,String cId,String aId,String btype) {
        if (mHttp == null) {
            mHttp = new HttpUtils(mContext, this);
        }
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", uId)
                .add("token", token)
                .add("type", type + "")
                .add("platform", platForm + "")
                .add("bid", bId)
                .add("cid", cId)
                .add("aid", aId)
                .add("btype", btype)
                .build();
        post(BuildConfig.URL_GET_SHARE_INFO, body);
    }

    @Override
    public boolean get(String url, Map<String, String> param) {
        return false;
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return JSON.parseObject(resultModel.getData(), ShareConfigData.class);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException, RemoteException {
        ShareConfigData shareConfigData = (ShareConfigData) resultModel.getDataModel();
        if(shareConfigData != null && !StringUtil.isNullorEmpty(shareConfigData.getUrl())){
            switch (mSharePLatForm) {
                case PLATFORM_QQ:
                    shareToQQ(shareConfigData.getTitle(), shareConfigData.getDesc(), shareConfigData.getUrl(), shareConfigData.getImg());
                    break;
                case PLATFORM_QQ_ZONE:
                    shareToQzone(shareConfigData.getTitle(), shareConfigData.getDesc(), shareConfigData.getUrl(), shareConfigData.getImg());
                    break;
                case PLATFORM_WECHAT:
                    shareToWX(shareConfigData.getTitle(), shareConfigData.getDesc(), shareConfigData.getUrl(), shareConfigData.getImg());
                    break;
                case PLATFORM_WECHAT_FRIEND:
                    shareToMoments(shareConfigData.getTitle(), shareConfigData.getDesc(), shareConfigData.getUrl(), shareConfigData.getImg());
                    break;
                case PLATFORM_SINA:
                    shareToSina(shareConfigData.getTitle(), shareConfigData.getDesc(), shareConfigData.getUrl(), shareConfigData.getImg());
                    break;
                case PLATFORM_COPY:
                    StringUtil.copy(mContext, shareConfigData.getTitle() + "  " + shareConfigData.getUrl());
                    Toast.makeText(mContext, "复制成功", Toast.LENGTH_SHORT).show();
                    break;
            }
            if (mDialog != null) {
                mDialog.dismiss();
            }
            if (mDialogFull != null) {
                mDialogFull.dismiss();
            }
        }
    }

    class ShareItemDeta {
        int iconRes;
        int text;

        public ShareItemDeta(int iconRes, int text) {
            this.iconRes = iconRes;
            this.text = text;
        }
    }

    public class ShareData {
        String title;
        String des;
        String linkurl;
        String imageurl;
        int type;
        Bitmap bitmap;
        IDownloadCallBack callBack;
    }


}
